package study.zookeeper.controller.curator;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/node")
public class _1NodeController {

    @Autowired
    private CuratorFramework client;

    @RequestMapping("/create")
    public String create(String path) throws Exception {
        String stat = client.create()
                .creatingParentContainersIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath(path);
        log.info(">>>>>> {}", stat);
        return "ok";
    }

    @RequestMapping("/setData")
    public String setData(String path, String data) throws Exception {
        Stat stat = client.setData()
                .forPath(path, data.getBytes());
        log.info("{}", stat);
        return "ok";
    }

    @RequestMapping("/getData")
    public String getData(String path) throws Exception {
        byte[] data = client.getData().forPath(path);
        return new String(data);
    }
}
